from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render

# Create your views here.
from .models import Book, Author


def insert_book(request):
    if request.method == 'POST':
        title = request.POST['title']
        author_name = request.POST['author_name']
        author_age = request.POST['author_age']
        author_gender = request.POST['author_gender']
        pub = request.POST['pub']
        price = request.POST['price']
        market_price = request.POST['market_price']
        try:
            book = Book.objects.create(title=title, pub=pub, price=price, market_price=market_price)
            book.authors.create(name=author_name, gender=author_gender, age=author_age)

        except Exception as e:
            print(f"insert book error as {e}")

        return HttpResponseRedirect(redirect_to='/bookstore/')

    elif request.method == 'GET':

        b = Book.objects.filter(is_delete=False)
        author = b.authors.all()

        return render(request, 'bookstore/index.html', {'books': b,'author':list(author)})

    else:
        html = '<h1>404 not found!</h1>'
        return HttpResponse(html)


def update_book(request, book_id):
    # query
    b1 = Book.objects.get(id=book_id)
    print(b1)
    if request.method == 'POST':
        # update
        b1.price = request.POST.get('price')
        b1.market_price = request.POST.get('market_price')
        b1.save()
        return HttpResponseRedirect('/bookstore/')

    if request.method == 'GET':
        return render(request, 'bookstore/update_book.html', {'book': b1})


def delete_book(request):  # book_id
    # try:
    #     b1 = Book.objects.get(id=book_id)
    #     b1.is_delete = True
    #     b1.save()
    # except Exception as e:
    #     print(f'delete book error as {e}')
    #
    # finally:
    #     return HttpResponseRedirect('/bookstore/')

    book_id = request.GET.get('book_id')
    if not book_id:
        return HttpResponse("请求异常")

    try:
        book = Book.objects.get(id=book_id, is_delete=False)
    except Exception as e:
        print(f"查找书籍错误 {e}")
        return HttpResponse("没有这本书")

    book.is_delete = True
    book.save()
    return HttpResponseRedirect('/bookstore/')
